/*
 * Galaxium Messenger
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;
using System.Net;

using Anculus.Core;

namespace Galaxium.Protocol.Msn.Soap
{
	internal class MsnSoapWebResponse : WebResponse
	{
		WebResponse _baseResponse;
		string _forcedContentType;
		
		public override long ContentLength
		{
			get { return _baseResponse.ContentLength; }
			set { _baseResponse.ContentLength = value; }
		}
		
		public override string ContentType
		{
			get
			{
				if (!string.IsNullOrEmpty (_forcedContentType))
					return _forcedContentType;
				
				return _baseResponse.ContentType;
			}
			set { _baseResponse.ContentType = value; }
		}

		public override WebHeaderCollection Headers
		{
			get { return _baseResponse.Headers; }
		}
		
		/*public override bool IsFromCache
		{
			get { return _baseResponse.IsFromCache; }
		}

		public override bool IsMutuallyAuthenticated
		{
			get { return _baseResponse.IsMutuallyAuthenticated; }
		}*/
		
		public override Uri ResponseUri
		{
			get { return _baseResponse.ResponseUri; }
		}
		
		public MsnSoapWebResponse (WebResponse baseResponse)
		{
			_baseResponse = baseResponse;
		}
		
		public MsnSoapWebResponse (WebResponse baseResponse, string forcedContentType)
			: this (baseResponse)
		{
			_forcedContentType = forcedContentType;
		}
		
		public override void Close ()
		{
			_baseResponse.Close ();
		}
		
		public override Stream GetResponseStream ()
		{
			//return _baseResponse.GetResponseStream ();
			
			Stream httpStream = _baseResponse.GetResponseStream ();
			Stream newStream = new MemoryStream ();
			byte[] buf = new byte[256];
			int read;
			int shownPercent = 0;
			
			while ((read = httpStream.Read (buf, 0, buf.Length)) > 0)
			{
				newStream.Write (buf, 0, read);
				
				int percent = (int)(((float)newStream.Length / ContentLength) * 100);
				
				if ((percent > 0) && (percent % 10 == 0) && (percent > shownPercent))
				{
					shownPercent = percent;
					Log.Debug ("Received {0}% ({1} of {2} bytes)", percent, newStream.Length, ContentLength);
				}
			}
			
			newStream.Seek (0, SeekOrigin.Begin);
			return newStream;
		}
	}
}
